package service;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;

import com.example.save.R;

import java.io.IOException;

public class MusicHelper {

    private MediaPlayer mediaPlayer;
    private Context context;
    private final int[] music=new int[]{R.raw.youyizhiguang,R.raw.river};
    private int musicIndex=0;
    private boolean prepared=false;

    public MusicHelper(Context context){
        this.context=context;
        createMediaPlayer();
    }


    private void createMediaPlayer(){
        mediaPlayer=new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    }

    public void play(){
        if(mediaPlayer.isPlaying()) {
            return;
        }
        if(prepared){
            mediaPlayer.start();
            return;
        }

        try{
            mediaPlayer.setDataSource(context, Uri.parse("android.resource://com.example.save/"+music[musicIndex]));
        } catch (Exception e) {
            e.printStackTrace();
        }

        mediaPlayer.prepareAsync();
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.start();
                prepared=true;
            }
        });
    }

    //暂停
    public void pause(){
        if(!mediaPlayer.isPlaying()){
            return;
        }
        mediaPlayer.pause();
    }

    //下一首
    public void next(){
        musicIndex=musicIndex+1;
        musicIndex=musicIndex%music.length;
        destroy();
        createMediaPlayer();
        play();
    }

    //销毁
    public void destroy(){
        if(mediaPlayer==null){
            return;
        }
        mediaPlayer.stop();
        mediaPlayer.release();
        mediaPlayer=null;
        prepared=false;
    }

}
